Computers are made to take a series of instructions and do something useful (or not). These algorithims are what make computers so useful! They allow computers to do what they do best, follow instructions and do them over and over again.
What happens if a decision has to be made?
What's nice about python is that a lot of the language can almost be read like english.
the only 'syntax' you have to deal with is tabs and a semi-colon
This is what an if statement looks like in python (in the general form)
if (some boolean value):
do some stuff if the boolean is true
In [16]:
if "daniel" == "daniel":
print ":D"
print "i'm here!"
in our bacon sandwhich example:
if (the slice of bread is an end piece):
skip it
else:
use bread to make sandwhich
In [41]:
#list_of_names = ["daniel", "niels", "vivian", "thomas"]
# how do i check if the fist name in the list is daniel?
if (list_of_names[0] == 'asdf'):
print "yes it is"
print "your name is daniel"
#print "no"
# how do i check if a name is in my list? if it is, print it!
if ("julia" in list_of_names):
print "yes he is in there"
else:
print "adding"
list_of_names.append("julia")
print list_of_names
# if the name isn't add it to the list
computers are great at doing something over and over again, one way we can tell a computer to iterate through something is using a 'for' loop
the for loop looks like this:
for some_variable in some_iterable:
do something
so, if we have an iterable (like a list), we can do something with each element in that list
In [12]:
list_of_names = ["daniel", "niels", "vivian", "thomas"]
for letter in "daniel":
if letter == "n":
break
print letter
print "hello"
'''
letter = "daniel"[0]
print letter
letter = "daniel"[1]
print letter
'''
Out[12]:
isn't that cool? now we don't have to change an index to get each one.
This brings us to a very important point:
In [5]:
# the 'name' variable in the previous example can be anything
# however you should use variable names so it is readable and
# self documenting
# we could've easily have written the follow to do the same thing
# coconut
## todo write code here
although not as common as the for loop, the while loop has a similar structure to the if statment. at the end of each cycle, the condition is re-evaluated. It will only exit the loop if the condition evaluates to false
be careful with while loops, it's possible to enter an infinite loop here.
In [5]:
# infinite while loop
flag = True
i = 0
while (flag):
print i
if i == 5:
flag = False
i += 1
I do not use while loops too much, you can pretty much accomplish the same thing using a for loop, however, sometimes i would use it if there are calculations to be done, and i know what case for it to stop in.
Sometimes when you are doing loops, you know a certain value is an exception and should be skipped over but you still need to iterate through the loop. How do you manage this?
although you can add an if statment, once it leaves the if block, the program will still loop through the rest of the loop block,
the continue statment solves this issue
essentially it says, stop everythign here, and return to the top, and continue as usual.
In [ ]:
list_of_names = ["daniel", "niels", "vivian", "thomas"]
# skip daniel but print the rest
# skip vivian, but print the rest
In [ ]:
list_of_names = ["daniel", "niels", "vivian", "thomas"]
'''
niels is the president of CSAPH, what if we had a list of names
but did not know where in the list he is?
we can loop through the list, and stop when we see his name
'''
In [ ]:
# hint: loop and variables
In [ ]:
# let's write the same thing using a while() loop
here is pseudo code taken from wikipedia on how to calculate a leap year: I have numbered the lines
If i was counting from year 0 to 2014 where would I put a break statement so i stop counting after I encounter the first year that is divisible by 4 but still not be a leap year?
A. before line 1
B. after line 1
C. after line 2
D. after line 3
E. after line 4
Wasn't that fun? bet you didn't know that there's more to leap years than you thought!
Let's actually write something where we assign some number to a variable, and then test to see if it is a leap year or not
In [ ]:
## leap year code
In [7]:
What if we are only interested in first names?
In [ ]:
Uh oh... how to we break apart the lines?
Do we see any kind of pattern?
In [ ]:
# string methods
Do we have enough to find first names now?
In [ ]:
Let's do some summary statistics
In [ ]:
What else can we do?
In [ ]:
Cool, let's have some mind teasers
which of the following will only print “hello world” exactly 3 times?
A.
while(True):
Print "hello world"
B.
for pizza in range(4):
if pizza == 4:
break
else:
print "hello world"
C.
for pizza in range(4):
if pizza == 3:
break
else:
print "hello world"
if pizza == 2:
continue
D.
for pizza in range(3):
continue
print "hello world"
E.
for pizza in range(3):
continue
print "hello world"
break
F.
for pizza in range(4):
if pizza == 3:
break
if pizza == 2:
continue
else:
print "hello world"
In [ ]:
here is a MCQ that will test your understanding of loops, conditions, and flow control
You probably would never write code like this but take this as an example:
What will this script return in standard output?
flag = False
while (not flag):
for pizza in range(5):
print pizza
if pizza == 5:
print "stop feeding me i'm full"
if pizza == 4:
continue
if pizza == 3:
break
flag = False
if pizza == 2:
flag = True
if pizza == int(str(1)):
print "more pizza please"
else:
continue
break
A. this will return an infinite loop
B. the values 0, 1, more pizza please, 2, 3, 4, 5, stop feeding me i’m full on separate lines
C. the values 0, 1, more pizza please, 2, 3, 4 on separate lines
D. the values 0, 1, more pizza please, 2, 3, stop feeding me i’m full on separate lines
E. the values 0, 1, more pizza please, 2, 3 on separate lines
F. the values 0, 1, 2, 3, 4, 5 on separate lines
G. the values 0, 1, 2, 3, 4 on separate lines
H. this will return nothing
In [ ]:
In [88]:
with open('testdata.txt') as file:
currentTotal = 0
numberOfPeople = 0
for line in file:
print int(line.split(',')[2].rstrip('\n'))
numberOfPeople += 1
currentTotal += int(line.split(',')[2].rstrip('\n'))
print "average: ", float(currentTotal)/numberOfPeople